<?php

namespace App\Http\Controllers\Admin;

use App\Http\Common\Constant;
use App\Http\Services\MemberServices;
use App\Models\CompanyBonusPoolIncomeLog;
use App\Models\CompanyIncome;
use App\Models\Member;
use App\Models\MemberBonusPoolIncomeLog;
use App\Models\MemberCash;
use App\Models\MemberRecommend;
use App\Models\StaffBonusPoolIncomeLog;
use App\Models\StaffTotalIncome;
use App\Models\StoreCash;
use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Log;


class FinanceController extends Controller
{

    // 会员提现申请列表
    public function index()
    {
        return view('admin.finance.index');
    }

    public function data(Request $request)
    {
        $model = DB::table('member_cash');
        if ($request->get('name')) {
            $model = $model->where('members.name', 'like', '%' . $request->get('name') . '%');
        }
        if ($request->get('phone')) {
            $model = $model->where('members.phone', 'like', '%' . $request->get('phone') . '%');
        }
        $res = $model
            ->select('member_cash.*', 'members.name', 'members.phone')
            ->leftJoin('members', 'members.id', '=', 'member_cash.member_id')
            ->orderBy('created_at', 'desc')
            ->paginate($request->get('limit', 30))->toArray();
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'data' => $res['data']
        ];
        return response()->json($data);
    }

    // 确认打款
    public function makeMoney(Request $request)
    {

        if ($request->get('ids')[0]) {
            $member_cash = MemberCash::where('id', $request->get('ids')[0])
                ->where('status', '1')
                ->first();
            if ($member_cash) {

                try {
                    DB::beginTransaction();

                    // 财务打款
                    $member_cash->status = 2;
                    $member_cash->user_id = Auth::user()->id;
                    $save = $member_cash->save();
                    if (!$save) {
                        throw new \Exception("财务打款失败");
                    }

                    $this->userBonusService($member_cash->money * Constant::MEMBER_CASH_SERVICE_PROPORTION, $member_cash->member_id, $member_cash->id);

                    DB::commit();
                    $data = [
                        'code' => 0,
                        'msg' => '打款成功',
                    ];
                    return response()->json($data);

                } catch (\Exception $exception) {
                    Log::error($exception);
                    DB::rollBack();
                    $data = [
                        'code' => -1,
                        'msg' => $exception->getMessage(),
                    ];
                    return response()->json($data);
                }

        } else {
            $data = [
                'code' => -1,
                'msg' => '失败',
            ];
            return response()->json($data);
            }
        }
    }

    // 用户提现返佣
    public function userBonusService($money, $member_id, $member_cash_id)
    {
        // 公司返佣
        $company_income = CompanyIncome::where('id', 1)->first();
        if ($company_income) {
            $company_income->total_money += $money * Constant::MEMBER_CASH_COMPANY_PROPORTION;
            $company_income->usable_money += $money * Constant::MEMBER_CASH_COMPANY_PROPORTION;
            $save = $company_income->save();
            if (!$save) {
                throw new \Exception("公司返佣写入失败");
            }
        } else {
            $company_income = new CompanyIncome();
            $company_income->id = 1;
            $company_income->total_money = $money * Constant::MEMBER_CASH_COMPANY_PROPORTION;
            $company_income->usable_money = $money * Constant::MEMBER_CASH_COMPANY_PROPORTION;
            $save = $company_income->save();
            if (!$save) {
                throw new \Exception("新增公司返佣写入失败");
            }
        }


        // 公司返佣日志
        $company_bonus_pool_income_log = new CompanyBonusPoolIncomeLog();
        $company_bonus_pool_income_log->money = $money * Constant::MEMBER_CASH_COMPANY_PROPORTION;
        $company_bonus_pool_income_log->proportion = Constant::MEMBER_CASH_COMPANY_PROPORTION;
        $company_bonus_pool_income_log->member_cash_id = $member_cash_id;
        $save = $company_bonus_pool_income_log->save();
        if (!$save) {
            throw new \Exception("公司返佣日志写入失败");
        }

        // 员工返佣
        $staff_total_income = StaffTotalIncome::where('id', 1)->first();
        if ($staff_total_income) {
            $staff_total_income->total_money = $money * Constant::MEMBER_CASH_STAFF_PROPORTION;
            $staff_total_income->useable_money = $money * Constant::MEMBER_CASH_STAFF_PROPORTION;
            $save = $staff_total_income->save();
            if (!$save) {
                throw new \Exception("员工返佣写入失败");
            }
        } else {
            $staff_total_income = new StaffTotalIncome();
            $staff_total_income->id = 1;
            $staff_total_income->total_money = $money * Constant::MEMBER_CASH_STAFF_PROPORTION;
            $staff_total_income->useable_money = $money * Constant::MEMBER_CASH_STAFF_PROPORTION;
            $save = $staff_total_income->save();
            if (!$save) {
                throw new \Exception("新增员工返佣写入失败");
            }
        }

        // 员工返佣日志
        $staff_bonus_pool_income_log = new StaffBonusPoolIncomeLog();
        $staff_bonus_pool_income_log->money = $money * Constant::MEMBER_CASH_STAFF_PROPORTION;
        $staff_bonus_pool_income_log->proportion = Constant::MEMBER_CASH_STAFF_PROPORTION;
        $staff_bonus_pool_income_log->member_cash_id = $member_cash_id;
        $save = $staff_bonus_pool_income_log->save();
        if (!$save) {
            throw new \Exception("员工返佣日志写入失败");
        }

        // 会员推荐人
        $member_recommend = MemberRecommend::where('recommend_id', $member_id)->first();
        if (isset($member_recommend->member_id)) {
            $member = Member::where('id', $member_recommend->member_id)->first();
            $member->useable_share_money += $money * Constant::MEMBER_CASH_MEMBER_PROPORTION;
            $member->total_share_money += $money * Constant::MEMBER_CASH_MEMBER_PROPORTION;
            $save = $member->save();
            if (!$save) {
                throw new \Exception("用户推荐人写入失败");
            }

            $member_bonus_pool_income_log = new MemberBonusPoolIncomeLog();
            $member_bonus_pool_income_log->member_id = $member_id;
            $member_bonus_pool_income_log->money = $money * Constant::MEMBER_CASH_MEMBER_PROPORTION;
            $member_bonus_pool_income_log->proportion = Constant::MEMBER_CASH_MEMBER_PROPORTION;
            $member_bonus_pool_income_log->member_cash_id = $member_cash_id;
            $save = $member_bonus_pool_income_log->save();
            if (!$save) {
                throw new \Exception("用户推荐人日志写入失败");
            }
        }

    }

    // 商家提现管理

    public function getStoreCashListData(Request $request)
    {
        $query = DB::table("store_cash as t1")
            ->leftJoin("store as t2","t1.store_id","=","t2.id")
            ->leftJoin("users as t3","t1.user_id", "=", "t3.id")
            ->select("t1.id", "t2.name as store_name", "t3.name as operator_name", "t1.money", "t1.proportion", "t1.status", "t1.created_at", "t1.updated_at");

        if ($name = $request->input("name")){
            $query = $query->where("t2.name", "like", "%".$name."%");
        }

        if ($begin_time = $request->input("begin_time")){
            $query = $query->where("t1.created_at", ">=", $begin_time);
        }

        if ($end_time = $request->input("end_time")){
            $query = $query->where("t1.created_at", "<", $end_time);
        }

        $res = $query->orderBy("t1.created_at","desc")->paginate(10)->toArray();
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res['total'],
            'data' => $res['data']
        ];
        return response()->json($data);
    }

    // todo 商家 提现 修改状态

    public function updateStoreCashStatus(Request $request)
    {
        $status = 2;
        $id = $request->input("ids");

        $storeCash = StoreCash::whereId($id[0])->first();
        if ($storeCash){
            try{
                DB::beginTransaction();
                StoreCash::serviceCharge($storeCash->id);
                //
                $storeCash->status = $status;
                $storeCash->save();
                DB::commit();
                $data = [
                    'code' => 0,
                    'msg' => '修改成功',

                ];
                return response()->json($data);

        }catch (\Exception $exception){
                DB::rollBack();
                Log::error($exception);
                $data = [
                    'code' => -1,
                    'msg' => '修改失败',

                ];
                return response()->json($data);

            }
        }
        $data = [
            'code' => 0,
            'msg' => '订单不存在',

        ];
        return response()->json($data);

    }

    public function memberRecommend()
    {
        return view('admin.finance.recommend');
    }

    public function memberRecommendData()
    {
        $memberService = new MemberServices();
        $list = $memberService->memberRecommendRebateData();
        return response()->json([
            'code' => 0,
            'msg'   => '正在请求中...',
            'count' => $list['total'],
            'data'  => $list['data']
        ]);
    }

}
